import logging

from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver

logging.basicConfig(level=logging.INFO)

class BasePage:
	_driver: WebDriver

	def __init__(self, driver: WebDriver = None):
		self._driver = driver

	#find方法需要处理各种异常弹窗的情形
	_black_list = [
		# (By.ID, 'tv_agree')
		(By.XPATH, '//*[@text="同意"]'),
		(By.ID, 'ib_close'),
		(By.XPATH, '//*[@text="下次再说"]')
	]

	_error_max = 3
	_error_count = 0
	def find(self, locator, value: str = None):
		logging.info(locator)
		logging.info(value)

		# try:
		# 	if isinstance(locator, tuple):
		# 		return self._driver.find_element(*locator)
		# 	else:
		# 		return self._driver.find_element(locator, value)
		try:
			ele = self._driver.find_element(*locator) if isinstance(locator, tuple) else self._driver.find_element(locator, value)
			self._error_count = 0
			# print('_error_count=%d' % self._error_count)
			return ele
		except Exception as e:
			# 异常次数过多，直接退出，报错异常
			if self._error_count > self._error_max:
				raise e


			# print('_error_count=%d' % self._error_count)
			while self._error_count <= self._error_max:
				self._error_count += 1
				for ele in self._black_list:
					# print(ele)
					eles = self._driver.find_elements(*ele)
					if len(eles) > 0:
						# print(self._driver.page_source)
						# print(eles)
						# print(eles[0])
						eles[0].click()
						# 继续寻找正常的控件
						return self.find(locator, value)
			self._error_count = 0
			logging.warn('黑名单没找到')
			return e

	def find_and_get_text1(self, locator, value: str = None):
		ele = self.find(locator, value)
		return ele.text

	def find_and_get_text(self, locator, value: str = None):
		logging.info(locator)
		logging.info(value)

		try:
			ele = self._driver.find_element(*locator) if isinstance(locator, tuple) else self._driver.find_element(locator, value)
			self._error_count = 0
			# print('_error_count=%d' % self._error_count)
			return ele.text
		except Exception as e:

			while self._error_count <= self._error_max:

				self._error_count += 1
				# print('_error_count=%d' % self._error_count)
				for ele in self._black_list:
					logging.info(ele)
					eles = self._driver.find_elements(*ele)
					if len(eles) > 1:
						eles[0].click()
						return self.find_and_get_text(locator, value)
			self._error_count = 0
			logging.warn('黑名单没找到')
			return e

	def get_toast(self):
		return self.find(By.XPATH, '//*[@class="android.widget.Toast"]').text

	def text(self, key):
		return (By.XPATH, '//*[@text="%s"]' % key)

	def find_by_text(self, key):
		return self.find(self.text(key))

